package com.softdev.system.generator.util;

import com.softdev.system.generator.entity.ClassInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * freemarker tool
 *
 * @author xuxueli 2018-05-02 19:56:00
 */
public class FreemarkerUtil {

    private final Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    /**
     * 初始化
     */
    public void init(String dbDir) {
        try {
            //configuration.setDirectoryForTemplateLoading(new File("E:\\04robot\\llmh2-db\\templates\\code-generator\\"));
            configuration.setDirectoryForTemplateLoading(new File(dbDir));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 设置异常处理器
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
    }

    /**
     * 传入需要转义的字符串进行转义
     * 20200503 zhengkai.blog.csdn.net
     */
    public String escapeString(String originStr) {
        return originStr.replaceAll("井", "\\#").replaceAll("￥", "\\$");
    }

    /**
     * process Template Into String
     *
     * @param template 目标
     * @param model    模型
     * @return 返回结果
     */
    public String processTemplateIntoString(Template template, Map<String, Object> model)
            throws IOException, TemplateException {
        ClassInfo codeJavaInfo = (ClassInfo) model.get("classInfo");
        //System.out.println("[bzm]processString -> classInfo=" + codeJavaInfo.getTableName() + ";" + codeJavaInfo.getClassName());
        StringWriter result = new StringWriter();
        template.process(model, result);
        return result.toString();
    }

    /**
     * process String
     *
     * @param templateName 模版
     * @param params       参数
     * @return 结果
     */
    public String processString(String templateName, Map<String, Object> params)
            throws IOException, TemplateException {
        // 获取模板
        Template template = this.configuration.getTemplate(templateName);
        //templateName = "E:/04robot/llmh2-db/templates/code-generator/swagger-ui*";
        //Template template = freemarkerConfig.getTemplate(templateName);
        return escapeString(processTemplateIntoString(template, params));
    }

}
